﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public class config
    {
        private static string _defaultconfigpath
        {
            get
            {
                return Environment.CurrentDirectory + "\\config.json";
            }
        }
        public string ProxyApi { get; set; }
        
        public int GetProxyCount { get; set; }
        public int ThreadWidth { get; set; }

        public string PollUrl { get; set; }
        public int TimeOut { get; set; }
        public string PollType { get; set; }
        public int ProxyExpire { get; set; }
        public static config GetConfig(string path=null)
        {
            if (string.IsNullOrEmpty(path))
                path = _defaultconfigpath;
            if (!File.Exists(path))
                DefaultConfig();
            var cstr = File.ReadAllText(path);
            var c = new config();
            try
            {
                c = JsonConvert.DeserializeObject<config>(cstr);
            }
            catch (Exception)
            {
                DefaultConfig();
                cstr = File.ReadAllText(path);
                c = JsonConvert.DeserializeObject<config>(cstr);
            }
            return c;
            
        }
        private static void DefaultConfig()
        {
            var c = DefaultSetting;
            File.WriteAllText(_defaultconfigpath, JsonConvert.SerializeObject(c));
        }
        public static config DefaultSetting
        {
            get
            {
                return new config
                {
                    ProxyApi = "http://api.xicidaili.com/free2016.txt",
                    GetProxyCount = 100,
                    ThreadWidth = 20,
                    TimeOut = 5000,
                    PollType = "POST",
                    PollUrl = "http://m.fangxinbao.com/wx/repersentVote.html?userId=38020",
                    ProxyExpire = 5 * 60 * 1000
                };
            }
        }
    }
}
